package com.hbu.product.hbumallproduct.utils;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableId;
import org.apache.ibatis.jdbc.SQL;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @ProjectName: hbu-mall
 * @Package: com.hbu.product.hbumallproduct.utils
 * @ClassName: SqlUtil
 * @Author: zxh
 * @Description:
 * @Date: 2022/11/17 21:57
 * @Version: 1.0
 */
public class SqlUtil {

    public static void updateUtil(Object updateEntity, SQL sql) {
        Map<String, Field> fieldHashMap = ReflectUtil.getFieldMap(updateEntity.getClass());
        for (String filedName : fieldHashMap.keySet()) {
            String underPrimary = StrUtil.toUnderlineCase(filedName);
            Field field = fieldHashMap.get(filedName);
            Object fieldValue = ReflectUtil.getFieldValue(updateEntity, field);
            if (!field.isAnnotationPresent(TableId.class) && fieldValue != null) {
                if (isNumber(fieldValue)) {
                    sql.SET(underPrimary + "=" + fieldValue);
                } else {
                    sql.SET(underPrimary + "= \"" + fieldValue + "\"");
                }
            }
        }
    }

    public static boolean isNumber(Object obj) {
        return (obj instanceof Integer || obj instanceof Long || obj instanceof Double || obj instanceof Float);
    }

}
